import store from './store'
import router from './router'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验证token

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.state.router.routers.length === 1) {
        // 获取菜单权限
        store.dispatch('GenerateRoutes').then((res) => { // 拉取用户信息
          if (res.length > 0) {
            router.addRoutes(res)
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          } else {
            Message({
              type: 'error',
              message: '该账号无菜单权限,即将返回登录页面',
              onClose: function () {
                store.dispatch('LogOut').then(() => {
                  next({ path: '/login' })
                })
              }
            })
          }
        })
      }
      else {
        // 设置默认路由
        if (to.path === '/') {
          const routers = store.state.router.routers
          return next({ path: routers[1].path })
        }
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.onError(() => {
  NProgress.done() // 结束Progress
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
